<?php
/**
 * Reconciliations Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class ReconciliationsController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    public $name = 'Reconciliations';
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    public $uses = array('Reconciliation', 'Aihexpense', 'Bmatch', 'Currency', 'Bank');
/**
 * Helpers used by the Controller
 *
 * @var array
 * @access public
 */
    public $helpers = array('Text', 'Html', 'Js');

    protected $paginate = array(
        'limit' => 10,
        );

/**
 * Before executing controller actions
 *
 * @return void
 * @access public
 */
    public function beforeFilter() {
        parent::beforeFilter();

        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

/**
 * Admin index
 *
 * @return void
 * @access public
 */
    public function admin_index() {
        $this->set('title_for_layout', __('BANK RECONCILIATION LIST'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $script = $this->getCheckedJS();
        $this->set('script', $script);
        
        $this->Reconciliation->recursive = 0;
        //
        $t_banks = $this->Reconciliation->find('all', array(
                        'fields' => array('DISTINCT Reconciliation.swift_code', 'Reconciliation.name_of_bank'),
                        'order' => array('Reconciliation.swift_code'),
                    )
                );
        $banks = '';
        foreach ($t_banks as $k => $v) {
            $banks .= '<option value="'.$v['Reconciliation']['swift_code'].'">'.$v['Reconciliation']['name_of_bank'].'</option>';
        }
        $this->set('banks', $banks);
        
        $this->paginate['Reconciliation']['order'] = 'Reconciliation.date DESC';
        
        $this->set('reconciliations', $this->paginate());
    }

    public function admin_match() {
        $this->set('title_for_layout', __('BANK RECONCILIATION MATCH'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);
        $bank = $this->params['named']['bank'];
        //
        $this->Reconciliation->recursive = 0;
        $t_banks = $this->Reconciliation->find('all', array(
                        'fields' => array('DISTINCT Reconciliation.swift_code', 'Reconciliation.name_of_bank'),
                        'order' => array('Reconciliation.swift_code'),
                    )
                );
        $banks = '';
        foreach ($t_banks as $k => $v) {
            $selected = ($v['Reconciliation']['swift_code']==$bank)?' selected="selected"':'';
            $banks .= '<option value="'.$v['Reconciliation']['swift_code'].'"'.$selected.'>'.$v['Reconciliation']['name_of_bank'].'</option>';
        }
        $this->set('banks', $banks);

        $from = $this->params['named']['from'];
        $this->set('from', $from);
        $to = $this->params['named']['to'];
        $this->set('to', $to);
        
        $conditions = array();
        if($bank!='all') {
            $conditions['Bmatch.swift_code'] = $bank;
        }
        $conditions['Bmatch.date >='] = $from;
        $conditions['Bmatch.date <='] = $to;
        
        $this->Bmatch->recursive = 0;
        
        $match_datas = $this->Bmatch->find('all', 
                array(
                    'conditions' => $conditions,
                    'order' => array('Bmatch.date'),
                )
            );
        $this->set('match_datas', $match_datas);
    }

/**
 * Admin add
 *
 * @return void
 * @access public
 */
    public function admin_add() {
        $this->set('title_for_layout', __('BANK RECONCILIATION DETAIL'));
        
        $redirect = array('action'=>'index');
        
        if (!empty($this->request->data)) {
//            php_debug($this->request->data);
            $this->request->data['Reconciliation']['amount'] = str_replace(',', '', $this->request->data['Reconciliation']['amount']);
            $this->request->data['Reconciliation']['date'] = $this->formatDate($this->request->data['Reconciliation']['date']);
            $this->request->data['Reconciliation']['currency_id'] = $this->request->data['Currency']['Currency'];
            
            // match
            $match = $this->Bmatch->find('first', array(
                'conditions' => array(
                    'Bmatch.reference_of_transaction' => $this->request->data['Reconciliation']['reference_of_transaction'], 
                ),
            ));
            $data = array(
                    'reference_of_transaction' => $this->request->data['Reconciliation']['reference_of_transaction'],
                    'name_of_bank' => $this->request->data['Reconciliation']['name_of_bank'], 
                    'address_of_bank' => $this->request->data['Reconciliation']['address_of_bank'], 
                    'bank_code' => $this->request->data['Reconciliation']['bank_code'], 
                    'branch_code' => $this->request->data['Reconciliation']['branch_code'], 
                    'swift_code' => $this->request->data['Reconciliation']['swift_code'], 
                    'amount' => $this->request->data['Reconciliation']['amount'], 
                    'currency_id' => $this->request->data['Reconciliation']['currency_id'], 
                    'currency' => $this->request->data['Reconciliation']['currency'], 
                    'date' => $this->request->data['Reconciliation']['date'], 
                    'status' => 1,
                );
            if(isset($match['Bmatch'])) {
                $data['id'] = $match['Bmatch']['id'];
                if($match['Bmatch']['status']===2) {
                    $data['status'] = 0;
                } 
                if($match['Bmatch']['e_amount']==$this->request->data['Reconciliation']['amount']) {
                    $data['status'] = 3;
                } else if($match['Bmatch']['e_amount']!='') {
                    $data['status'] = 0;
                }
            } 
            
            $this->Reconciliation->create();
            if ($this->Reconciliation->save($this->request->data)) {
                $this->Reconciliation->bmatch($data);
                //$this->Session->setFlash(__('The Bank has been saved'), 'default', array('class' => 'success'));
                $this->redirect($redirect);
            } else {
                $this->Session->setFlash(__('The Bank could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            } 
        }
        
        $currencies = $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name'), 'order' => array('Currency.name ASC')));
        $this->set(compact('currencies'));

        $scriptDatePicker = $this->datePicker();
        $this->set('scriptDatePicker', $scriptDatePicker);
        
    }

/**
 * Admin edit
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('BANK RECONCILIATION DETAIL'));

        $redirect = array('action'=>'index');
        
        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Bank'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        if (!empty($this->request->data)) {
//            php_debug($this->request->data);
            $this->request->data['Reconciliation']['amount'] = str_replace(',', '', $this->request->data['Reconciliation']['amount']);
            $this->request->data['Reconciliation']['date'] = $this->formatDate($this->request->data['Reconciliation']['date']);
            $this->request->data['Reconciliation']['currency_id'] = $this->request->data['Currency']['Currency'];
            
            // match
            $conditions = array(
                    'Bmatch.reference_of_transaction' => $this->request->data['Reconciliation']['reference_of_transaction'], 
                );
            $match = $this->Bmatch->find('first', array('conditions' => $conditions));
            $data = array(
                    'reference_of_transaction' => $this->request->data['Reconciliation']['reference_of_transaction'],
                    'name_of_bank' => $this->request->data['Reconciliation']['name_of_bank'], 
                    'address_of_bank' => $this->request->data['Reconciliation']['address_of_bank'], 
                    'bank_code' => $this->request->data['Reconciliation']['bank_code'], 
                    'branch_code' => $this->request->data['Reconciliation']['branch_code'], 
                    'swift_code' => $this->request->data['Reconciliation']['swift_code'], 
                    'amount' => $this->request->data['Reconciliation']['amount'], 
                    'currency_id' => $this->request->data['Reconciliation']['currency_id'], 
                    'currency' => $this->request->data['Reconciliation']['currency'], 
                    'date' => $this->request->data['Reconciliation']['date'], 
                    'status' => 1,
                );
            if(isset($match['Bmatch'])) {
                $data['id'] = $match['Bmatch']['id'];
                if($match['Bmatch']['status']===2) {
                    $data['status'] = 0;
                } 
                if($match['Bmatch']['e_amount']==$this->request->data['Reconciliation']['amount']) {
                    $data['status'] = 3;
                } else if($match['Bmatch']['e_amount']!='') {
                    $data['status'] = 0;
                }
            }
            
            if ($this->Reconciliation->save($this->request->data)) {
                $this->Aihexpense->bmatch($data);
                //$this->Session->setFlash(__('The Bank has been saved'), 'default', array('class' => 'success'));
                $this->redirect($redirect);
            } else {
                $scriptDatePicker = $this->datePicker();
                $this->set('scriptDatePicker', $scriptDatePicker);
                $this->Session->setFlash(__('The Bank could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Reconciliation->read(null, $id);
            
            $currencies = $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name'),'order' => array('Currency.name ASC')));
            $this->set(compact('currencies'));

            $scriptDatePicker = $this->datePicker();
            $this->set('scriptDatePicker', $scriptDatePicker);

        }
    }

/**
 * Admin delete
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_delete($id = null) {
        
        $redirect = array('action'=>'index');
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid id'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        $bank = $this->Reconciliation->find('first', array(
            'conditions' => array(
                'id' => $id,
            ),
        ));
        if (isset($bank['Reconciliation'])) {
            if ($this->Reconciliation->delete($id)) {
                // Reconciliation
                $match = $this->Bmatch->find('first', array('conditions' => array('Bmatch.reference_of_transaction' => $bank['Reconciliation']['reference_of_transaction'])));
                if($match['Bmatch']['e_amount']=='' && $match['Bmatch']['e_name_of_bank']=='') {
                    // delete
                    $this->Reconciliation->del_bmatch($match['Bmatch']['id']);
                } else {
                    $data['id'] = $match['Bmatch']['id'];
                    $data['amount'] = '';
                    $data['name_of_bank'] = '';
                    $this->Reconciliation->bmatch($data);
                }
                //$this->Session->setFlash(__('Bank deleted'), 'default', array('class' => 'success'));
                $this->redirect($redirect);
            }
        } else {
//            $this->Session->setFlash(__('Invalid id '), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
    }
    
    public function admin_checkreftransunique($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $banks = $this->Reconciliation->find('first', array('fields' => array('Reconciliation.reference_of_transaction'), 'conditions' => array('Reconciliation.reference_of_transaction' => $id,)));
            if ($banks) {
                $success = true;
                $success = $this->Reconciliation->encodeData(array('success' => $success, 'isExsist' => '1'), array('json' => true, 'trim' => false));
            }else{
                $success = true;
                $success = $this->Reconciliation->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Reconciliation->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
        }
        $this->set('success', $success);
    }
    
    public function getCheckedJS(){
        
        $output = "
             $(function() {
                $(function() {
                    $('.checkall').click(function () {
                        if($('#checkflag').val() == '0'){
                            $('.chk-payment-schedule').attr('checked', true);
                            $('#checkflag').val(1);
                            $('.checkall').html('Uncheck All');
                        }else{
                            $('#checkflag').val(0);
                            $('.checkall').html('Check All');
                            $('.chk-payment-schedule').removeAttr('checked');
                        }
                    });
                    $('.chk-payment-schedule').click(function () {
                        if($('.chk-payment-schedule').filter(':not(:checked)').length > 0){
                            $('#checkflag').val(0);
                            $('.checkall').html('Check All');
                        }else{
                            $('#checkflag').val(1);
                            $('.checkall').html('Uncheck All');
                        }
                    });	
                });   
            });
        ";
        return $output;
    }
    
    public function datePicker() {
        $output = "$(function() {
                        $('#ReconciliationDate').datepicker({ changeYear: true, dateFormat: 'm/d/yy'});
                        return false;
                    });";
        return $output;
    }
    
    public function formatDate($str) {
        $temp = explode('/', $str);
        return $temp[2] . '-' . $temp[0] . '-' . $temp[1];
    }

    public function scriptSearchBox() {
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    var sb = $('select#match_bank_id option::selected');
                    var t_from = $('#match_from_id').val().split('/');
                    var from = new Date($('#match_from_id').val());
                    var t_to = $('#match_to_id').val().split('/');
                    var to = new Date($('#match_to_id').val());
                    var count = (to-from)/(1000*60*60*24);
                    if(count>=0) {
                        var q_from = t_from[2]+'-'+t_from[0]+'-'+t_from[1];
                        var q_to = t_to[2]+'-'+t_to[0]+'-'+t_to[1];
                        var temp = sb.val()+'/from:'+q_from+'/to:'+q_to;
                        $(location).attr('href','" . Router::url('/admin/reconciliations/match/bank:', true) . "' + temp);
                    } else {
                        alert('To date must greater than from date. Please try again!');
                    }
                });
            });";
        return $output;
    }

}
?>